package com.bolt.support.json.jackjson.component;

import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.ser.DefaultSerializerProvider;
import com.fasterxml.jackson.databind.ser.SerializerFactory;

import java.util.Collection;

public class NullValueSerializerProvider extends DefaultSerializerProvider {

    public NullValueSerializerProvider() {
        super();
    }

    protected NullValueSerializerProvider(SerializerProvider src, SerializationConfig config, SerializerFactory f) {
        super(src, config, f);
    }

    @Override
    public DefaultSerializerProvider createInstance(SerializationConfig config, SerializerFactory jsf) {
        return new NullValueSerializerProvider(this, config, jsf);
    }

    @Override
    public JsonSerializer<Object> findNullValueSerializer(BeanProperty property) throws JsonMappingException {
        if (isStringType(property)) {
            return CustomizeNullJsonComponent.NULL_STRING_SERIALIZER;
        } else if (isArrayType(property)) {
            return CustomizeNullJsonComponent.NULL_ARRAY_SERIALIZER;
        } else {
            return super.findNullValueSerializer(property);
        }
    }

    /**
     * 是否是数组
     */
    private boolean isArrayType(BeanProperty property) {
        Class<?> clazz = property.getType().getRawClass();
        return clazz.isArray() || Collection.class.isAssignableFrom(clazz);
    }

    /**
     * 是否是String
     */
    private boolean isStringType(BeanProperty property) {
        Class<?> clazz = property.getType().getRawClass();
        return CharSequence.class.isAssignableFrom(clazz) || Character.class.isAssignableFrom(clazz);
    }
}